(function() {

    var ImageManager = function() {
        this._loadList = {};
        this._readyFuncs = [];
        this._loaded = 0;
    }

    ImageManager.prototype._load = function(image, callback) {
        var self = this;
        var img = new Image();
        self._loadList[image.id] = false;
        img.onload = function() {
            self._loadList[image.id] = img;
            self._loaded++;
            if (callback) {
                callback(self._loaded);
            }
            if (self._isReady()) {
                self._readyFuncs.forEach(function(f) {
                    f.call(self);
                });
            };
        }
        img.src = image.src;
    },

    ImageManager.prototype.load = function(images, stateChange) {
        var self = this;
        images = (images instanceof Array ? images : [images]);
        stateChange = (stateChange ? stateChange : undefined);
        images.forEach(function(image) {
            self._load(image, stateChange);
        });
    },

    ImageManager.prototype.get = function(id) {
        return this._loadList[id];
    },

    ImageManager.prototype.onReady = function() {
        for (var i=0, l=arguments.length; i < l; i++) {
            this._readyFuncs.push(arguments[i]);
        }
    },

    ImageManager.prototype._isReady = function() {
        var ready = true;
        for (var id in this._loadList) {
            if (!this._loadList[id]) {
                ready = false;
            }
        }
        return ready;
    }

    window.ImageManager = ImageManager;

})();